package com.action;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;

import javax.servlet.http.HttpServletResponse;

import com.bean.RecordBean;
import com.bean.UserBean;
import com.dao.RenewDao;
import com.dao.UserDao;
import com.exception.DBException;
import com.exception.RenewException;
import com.exception.UserException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class RenewAction
{

	private void LIST_JSON_SEND(HttpServletResponse response,
			ArrayList<RecordBean> list)
	{
		Gson gson = new GsonBuilder().setDateFormat("MM-dd-yyyy").create();
		String json = gson.toJson(list);
		response.setContentType("application/json");
		try
		{
			Writer w = response.getWriter();
			w.write(json);
			w.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	private void BEAN_JSON_SEND(HttpServletResponse response,
			RecordBean recordBean)
	{
		Gson gson = new GsonBuilder().setDateFormat("MM-dd-yyyy").create();
		String json = gson.toJson(recordBean);
		response.setContentType("application/json");
		try
		{
			Writer w = response.getWriter();
			w.write(json);
			w.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	public void getRenewInfo(HttpServletResponse response, RecordBean recordBean)
			throws DBException, UserException, RenewException
	{
		UserBean userBean = new UserBean();
		userBean.setUserID(recordBean.getUserID());
		UserDao userDao = new UserDao();
		if (!userDao.ifUserExist(userBean))
		{
			throw new UserException("user is not exist");
		}
		RenewDao renewDao = new RenewDao();
		if(!renewDao.ifUserBorrow(recordBean))
		{
			throw new RenewException("this user does't borrow anything");
		}
		ArrayList<RecordBean> list = renewDao.GetRenewRecord(recordBean);
		this.LIST_JSON_SEND(response, list);
	}

	public void renewIns(HttpServletResponse response, RecordBean recordBean)
			throws DBException, RenewException
	{
		RenewDao renewDao = new RenewDao();
		// if the record is not exist,throw a exception
		if (!renewDao.ifReordExist(recordBean))
		{
			throw new RenewException("record is not exist");
		}
		// avoid to renew the instrument after backing
		if (!renewDao.ifRecordBack(recordBean))
		{
			throw new RenewException("can't renew the instrument");
		}

		renewDao.renewIns(recordBean);
		
		renewDao.getRenewResult(recordBean);
		
		this.BEAN_JSON_SEND(response, recordBean);

	}

}
